<template>
  <div class="container mx-auto px-4 py-6">
    <div class="flex items-center mb-6">
      <button @click="$router.back()" class="mr-4 p-2 text-gray-600 hover:text-gray-800">
        <ArrowLeftIcon class="h-6 w-6" />
      </button>
      <h2 class="text-2xl font-semibold text-gray-800">
        {{ isEdit ? '编辑报废记录' : '设备报废' }}
      </h2>
    </div>

    <div class="bg-white rounded-xl shadow-lg p-6">
      <form @submit.prevent="handleSubmit" class="space-y-6">
        <!-- 设备选择 -->
        <div>
          <label for="equipmentId" class="block text-sm font-medium text-gray-700 mb-2">
            选择设备 <span class="text-red-500">*</span>
          </label>
          <select 
            id="equipmentId" 
            v-model="form.equipmentId" 
            required
            class="w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
            :disabled="isEdit"
          >
            <option value="">请选择设备</option>
            <option v-for="equipment in equipmentList" :key="equipment.id" :value="equipment.id">
              {{ equipment.name }} ({{ equipment.code }}) - {{ equipment.category }}
            </option>
          </select>
        </div>

        <!-- 报废日期 -->
        <div>
          <label for="scrapDate" class="block text-sm font-medium text-gray-700 mb-2">
            报废日期 <span class="text-red-500">*</span>
          </label>
          <input 
            type="date" 
            id="scrapDate" 
            v-model="form.scrapDate" 
            required
            class="w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
          />
        </div>

        <!-- 报废原因 -->
        <div>
          <label for="scrapReason" class="block text-sm font-medium text-gray-700 mb-2">
            报废原因 <span class="text-red-500">*</span>
          </label>
          <select 
            id="scrapReason" 
            v-model="form.scrapReason" 
            required
            class="w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
          >
            <option value="">请选择报废原因</option>
            <option value="NATURAL_AGING">自然老化</option>
            <option value="SERIOUS_DAMAGE">严重损坏</option>
            <option value="TECHNICAL_OBSOLETE">技术淘汰</option>
            <option value="LOST">丢失</option>
            <option value="OTHER">其他</option>
          </select>
        </div>

        <!-- 报废方式 -->
        <div>
          <label for="scrapMethod" class="block text-sm font-medium text-gray-700 mb-2">
            报废方式 <span class="text-red-500">*</span>
          </label>
          <select 
            id="scrapMethod" 
            v-model="form.scrapMethod" 
            required
            class="w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
          >
            <option value="">请选择报废方式</option>
            <option value="DISPOSAL">销毁处理</option>
            <option value="SALE">变卖</option>
            <option value="DONATION">捐赠</option>
            <option value="RETURN">退回</option>
          </select>
        </div>

        <!-- 处置价值 -->
        <div>
          <label for="disposalValue" class="block text-sm font-medium text-gray-700 mb-2">
            处置价值 (元)
          </label>
          <input 
            type="number" 
            id="disposalValue" 
            v-model="form.disposalValue" 
            step="0.01"
            min="0"
            class="w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
          />
        </div>

        <!-- 责任人 -->
        <div>
          <label for="responsiblePerson" class="block text-sm font-medium text-gray-700 mb-2">
            责任人 <span class="text-red-500">*</span>
          </label>
          <input 
            type="text" 
            id="responsiblePerson" 
            v-model="form.responsiblePerson" 
            required
            placeholder="请输入责任人姓名"
            class="w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
          />
        </div>

        <!-- 审批人 -->
        <div>
          <label for="approvalPerson" class="block text-sm font-medium text-gray-700 mb-2">
            审批人
          </label>
          <input 
            type="text" 
            id="approvalPerson" 
            v-model="form.approvalPerson" 
            placeholder="请输入审批人姓名"
            class="w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
          />
        </div>

        <!-- 备注 -->
        <div>
          <label for="remark" class="block text-sm font-medium text-gray-700 mb-2">
            备注
          </label>
          <textarea 
            id="remark" 
            v-model="form.remark" 
            rows="4"
            placeholder="请输入备注信息"
            class="w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
          ></textarea>
        </div>

        <!-- 操作按钮 -->
        <div class="flex justify-end space-x-4 pt-6 border-t">
          <button 
            type="button" 
            @click="$router.back()" 
            class="px-6 py-2 border border-gray-300 text-gray-700 rounded-md hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2"
          >
            取消
          </button>
          <button 
            type="submit" 
            :disabled="loading"
            class="px-6 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {{ loading ? '保存中...' : (isEdit ? '更新' : '保存') }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ArrowLeftIcon } from '@heroicons/vue/24/outline'
import request from '@/utils/request'

const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const equipmentList = ref([])

// 表单数据
const form = reactive({
  equipmentId: '',
  scrapDate: '',
  scrapReason: '',
  scrapMethod: '',
  disposalValue: '',
  responsiblePerson: '',
  approvalPerson: '',
  remark: ''
})

// 计算属性
const isEdit = computed(() => !!route.params.id)

// 加载设备列表
const loadEquipmentList = async () => {
  try {
    const response = await request.get('/equipment/list?pageSize=1000')
    equipmentList.value = response.data.records || []
  } catch (error) {
    console.error('加载设备列表失败:', error)
    showMessage('加载设备列表失败', 'error')
  }
}

// 加载报废记录详情
const loadScrapRecord = async () => {
  if (!isEdit.value) return
  
  try {
    loading.value = true
    const response = await request.get(`/equipment-scrap/${route.params.id}`)
    const record = response.data
    
    Object.assign(form, {
      equipmentId: record.equipmentId,
      scrapDate: record.scrapDate,
      scrapReason: record.scrapReason,
      scrapMethod: record.scrapMethod,
      disposalValue: record.disposalValue,
      responsiblePerson: record.responsiblePerson,
      approvalPerson: record.approvalPerson,
      remark: record.remark
    })
  } catch (error) {
    console.error('加载报废记录失败:', error)
    showMessage('加载报废记录失败', 'error')
  } finally {
    loading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    loading.value = true
    
    const requestData = {
      equipmentId: parseInt(form.equipmentId),
      scrapDate: form.scrapDate,
      scrapReason: form.scrapReason,
      scrapMethod: form.scrapMethod,
      disposalValue: form.disposalValue ? parseFloat(form.disposalValue) : null,
      responsiblePerson: form.responsiblePerson,
      approvalPerson: form.approvalPerson,
      remark: form.remark
    }
    
    if (isEdit.value) {
      await request.put(`/equipment-scrap/${route.params.id}`, requestData)
      showMessage('报废记录更新成功', 'success')
    } else {
      await request.post('/equipment-scrap', requestData)
      showMessage('设备报废成功', 'success')
    }
    
    router.push('/equipment-scrap')
    
  } catch (error) {
    console.error('保存报废记录失败:', error)
    showMessage('保存报废记录失败', 'error')
  } finally {
    loading.value = false
  }
}

// 简单消息显示函数
const showMessage = (message, type = 'info') => {
  const messageEl = document.createElement('div')
  messageEl.className = `fixed top-4 right-4 px-6 py-3 rounded-lg text-white z-50 ${
    type === 'success' ? 'bg-green-500' :
    type === 'warning' ? 'bg-yellow-500' :
    type === 'error' ? 'bg-red-500' :
    'bg-blue-500'
  }`
  messageEl.textContent = message
  document.body.appendChild(messageEl)

  setTimeout(() => {
    if (document.body.contains(messageEl)) {
      document.body.removeChild(messageEl)
    }
  }, 3000)
}

// 初始化
onMounted(() => {
  loadEquipmentList()
  if (isEdit.value) {
    loadScrapRecord()
  } else {
    // 设置默认报废日期为今天
    form.scrapDate = new Date().toISOString().split('T')[0]
  }
})
</script>
